package com.roger.myHome.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.roger.myHome.entity.BloodSugarCurveData;
import com.roger.myHome.entity.ColumnData;
import com.roger.myHome.entity.PieData;
import com.roger.myHome.entity.qto.AvgExpenseQry;
import com.roger.myHome.entity.qto.TotalExpenseReq;
import com.roger.myHome.entity.vo.BloodSugarDetailData;
import com.roger.myHome.entity.vo.BloodSugarExceptionCurveData;
import com.roger.myHome.entity.vo.BloodSugarOrderByTime;
import com.roger.myHome.entity.vo.OneDayBloodGlucose;
import com.roger.myHome.mapper.ReportMapper;
import com.roger.myHome.service.ReportService;
import com.roger.myHome.util.DateUtil;
import com.roger.myHome.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Resource
    private ReportMapper reportMapper;

    @Override
    public String getBloodSugarCurveReport() {
        String maxMeasureTime = DateUtil.today() + " 23:59:59";

        List<BloodSugarCurveData> list = reportMapper.selectBloodSugarCurveReport(maxMeasureTime);

        Collections.reverse(list);

        Map<String, List> hp = new HashMap<>();

        List<String> list1 = new ArrayList<>();
        List<Float> list2 = new ArrayList<>();

        for(BloodSugarCurveData bloodSugar : list){
            list1.add(bloodSugar.getMeasureTime());
            list2.add(bloodSugar.getBloodSugarValue());
        }

        hp.put("measureTime", list1);
        hp.put("bloodSugarValue",list2);

        return JSONArray.toJSONString(hp);
    }

    @Override
    public String getBloodSugarExceptionCurveReport() {
        String maxMeasureTime = DateUtil.today() + " 23:59:59";

        List<BloodSugarExceptionCurveData> list = reportMapper.selectBloodSugarExceptionCurveReport(maxMeasureTime);

        Collections.reverse(list);

        Map<String, List> hp = new HashMap<>();

        List<String> list1 = new ArrayList<>();
        List<Float> list2 = new ArrayList<>();

        for(BloodSugarExceptionCurveData bloodSugar : list){
            list1.add(bloodSugar.getMeasureTime());
            list2.add(bloodSugar.getBloodSugarException());
        }

        hp.put("measureTime", list1);
        hp.put("bloodSugarException",list2);

        return JSONArray.toJSONString(hp);
    }

    @Override
    public String getBloodSugarPieReport() {
        Float totalSize = 50F;
        List<BloodSugarOrderByTime> list = reportMapper.selectBloodSugarOrderByTime();
        Float high = 0F;
        Float low = 0F;
        Float common = 0F;
        for (BloodSugarOrderByTime obj : list) {
            if (obj.getBloodSugarLevel().equals("偏高")) {
                high ++;
            }
            if (obj.getBloodSugarLevel().equals("偏低")) {
                low ++;
            }
            if (obj.getBloodSugarLevel().equals("正常")) {
                common ++;
            }
        }

        Float f1 = high / totalSize;

        Float f2 = low / totalSize;

        Float f3 = common / totalSize;

        List<PieData> resultList = new ArrayList<>();
        resultList.add(new PieData("偏高",f1 * 100F));
        resultList.add(new PieData("偏低",f2 * 100F));
        resultList.add(new PieData("正常",f3 * 100F));

        return StringUtils.listToJson(resultList);
    }

    @Override
    public String getExpenseColumnReport(Long userId) {
        TotalExpenseReq req = new TotalExpenseReq();
        String month = DateUtil.currentMonth();
        String[] array = month.split("-");
        int year = Integer.valueOf(array[0]);
        req.setYear(year);
        req.setUserId(userId);
        List<ColumnData> resultList = reportMapper.selectExpenseByYear(req);
        return StringUtils.listToJson(resultList);
    }


    @Override
    public String bloodSugarMeasureTimes() {
        Map<String, String> hp = new HashMap<>();

        List<BloodSugarOrderByTime> list = reportMapper.selectBloodSugarOrderByTime();
        //Float avg = reportMapper.selectBloodSugarAvg();
        Integer high = 0;
        Integer low = 0;
        Integer common = 0;
        Float total = 0F;
        for (BloodSugarOrderByTime obj : list) {
            if (obj.getBloodSugarLevel().equals("偏高")) {
                high ++;
            }
            if (obj.getBloodSugarLevel().equals("偏低")) {
                low ++;
            }
            if (obj.getBloodSugarLevel().equals("正常")) {
                common ++;
            }
            total += obj.getBloodSugarValue();
        }
        Float avg = total / 50;

        Collections.sort(list, new Comparator<BloodSugarOrderByTime>() {
            @Override
            public int compare(BloodSugarOrderByTime u1, BloodSugarOrderByTime u2) {
                Float diff = u1.getBloodSugarValue() - u2.getBloodSugarValue();
                if (diff < 0) {
                    return 1;
                }else if (diff > 0) {
                    return -1;
                }
                return 0; //相等为0
            }
        }); // 排序

        int c = 0;
        float s = 0F;
        for (BloodSugarOrderByTime obj : list) {
            if ("空腹".equalsIgnoreCase(obj.getTimePeriod())) {
                c++;
                s += obj.getBloodSugarValue();
            }
        }

        BloodSugarOrderByTime highObj = list.get(0);
        BloodSugarOrderByTime lowObj = list.get(49);
        String result = "<html>\n" +
                "<head>\n" +
                "<meta charset=\"utf-8\">\n" +
                "</head>\n" +
                "<body>\n" +
                "    <h2 style='font-size:16px;'>数据分析结果</h2>\n" +
                "    <p style='font-size:14px;'>[" + high + "次偏高," + common + "次正常," + low + "次偏低]</p>\n" +
                "    <p style='font-size:14px;'>[平均血糖值:" + avg + "]</p>\n" +
                "    <p style='font-size:14px;'>[空腹平均血糖值:" + (s / c) + "]</p>\n" +
                "    <p style='font-size:14px;'>[最高值:" + highObj.getBloodSugarValue() + ",测量时间:" + highObj.getMeasureTime() + "]</p>\n" +
                "    <p style='font-size:14px;'>[最低值:" + lowObj.getBloodSugarValue() + ",测量时间:" + lowObj.getMeasureTime() + "]</p>\n" +
                "</body>\n" +
                "</html>";
        hp.put("result", result);

        return JSONArray.toJSONString(hp);
    }

    @Override
    public String getAvgExpense(Long userId) {
        String[] yearMonth = DateUtil.currentMonth().split("-");
        Integer year = Integer.valueOf(yearMonth[0]);
        Integer month = Integer.valueOf(yearMonth[1]);
        AvgExpenseQry qry = new AvgExpenseQry();
        qry.setYear(year);
        qry.setMonth(month);
        qry.setUserId(userId);
        BigDecimal avg = reportMapper.getAvgExpense(qry);

        Map<String, String> hp = new HashMap<>();
        hp.put("data",month + "个月平均消费:" + avg + "元");
        return JSONArray.toJSONString(hp);
    }

    @Override
    public String morningBloodSugarReport() {
        Map<String, List> hp = new HashMap<>();

        List<OneDayBloodGlucose> list = reportMapper.listOneDayBloodGlucose();
        Collections.reverse(list);

        List<String> categories = new ArrayList<>();
        List<Float> data1 = new ArrayList<>();
        List<Float> data2 = new ArrayList<>();
        for (OneDayBloodGlucose obj : list) {
            categories.add(obj.getYmd());
            data1.add(obj.getFastingGlucose());
            data2.add(obj.getPgb());
        }

        hp.put("categories", categories);
        hp.put("data1",data1);
        hp.put("data2",data2);

        return JSONArray.toJSONString(hp);
    }

    @Override
    public String getBloodSugarByIndex(int index) {
        Map<String, String> hp = new HashMap<>();

        String maxMeasureTime = DateUtil.today() + " 23:59:59";

        List<BloodSugarDetailData> list = reportMapper.selectBloodSugarDetailReport(maxMeasureTime);

        Collections.reverse(list);

        BloodSugarDetailData entity = list.get(index);

        log.info("{},{}", index,entity);

        float value = entity.getBloodSugarValue();

        String time = entity.getMeasureTime();

        String timePeriod = entity.getTimePeriod();

        String result = "<html>\n" +
                "<head>\n" +
                "<meta charset=\"utf-8\">\n" +
                "</head>\n" +
                "<body>\n" +
                "    <h2 style='font-size:16px;'>测量结果</h2>\n" +
                "    <p style='font-size:14px;'>[测量时间:" + time + "]</p>\n" +
                "    <p style='font-size:14px;'>[测量时间段:" + timePeriod + "]</p>\n" +
                "    <p style='font-size:14px;'>[测量值:" + value + "mmol/L]</p>\n" +
                "</body>\n" +
                "</html>";
        hp.put("result", result);

        return JSONArray.toJSONString(hp);

    }

    public static void main(String[] args) {
        Float count1 = 11F;
        Float count2 = 2F;
        Float total = 13F;
        Float f1 = count1 / total;
        Float f2 = count2 / total;
        System.out.println(f1 * 100F + "," + f2 * 100F);
    }

}
